<%@ page import="javax.jcr.Repository,
         org.apache.jackrabbit.j2ee.RepositoryAccessServlet,
         org.apache.jackrabbit.util.Text,
         javax.jcr.Session,
         javax.jcr.SimpleCredentials,
         javax.jcr.query.Query,
         javax.jcr.query.RowIterator,
         java.text.NumberFormat,
         javax.jcr.query.Row,
         javax.jcr.Node,
         java.net.URLEncoder,
         java.text.SimpleDateFormat,
         java.text.DateFormat,
         java.util.List,
         java.util.ArrayList,
         java.util.Iterator,
         javax.jcr.Value,
         javax.jcr.RepositoryException,
         javax.mail.internet.MimeMessage,
         org.apache.commons.fileupload.*,
         org.apache.commons.fileupload.servlet.*,
         org.apache.commons.fileupload.disk.*,
         org.apache.commons.io.IOUtils,
         java.io.*,
         java.util.zip.*,
         java.util.*,
         java.net.*,
         org.ilookinto.util.NodeUtil,
         org.ilookinto.jr.JCRStoreBean
         "
         %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">


<%

    Session jcrSession = null;
    try {
      Repository rep;
      if (ServletFileUpload.isMultipartContent(request)) {

        try {
          rep = RepositoryAccessServlet.getRepository(pageContext.getServletContext());
          jcrSession = rep.login(new SimpleCredentials("admin", "admin".toCharArray()));
        } catch (Throwable e) {
%>
Error while accessing the repository: <font color="red"><%= Text.encodeIllegalXMLCharacters(e.getMessage())%></font><br>
Check the configuration or use the <a href="admin/">easy setup</a> wizard.<%
          return;
        }

        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        //Create a progress listener
        final HttpSession mysession = session;
        ProgressListener progressListener = new ProgressListener() {

          private long megaBytes = -1;

          public void update(long pBytesRead, long pContentLength, int pItems) {
            long mBytes = pBytesRead / 1000000;
            if (megaBytes == mBytes) {
              return;
            }
            megaBytes = mBytes;
            mysession.setAttribute("readed", pBytesRead + "");
            mysession.setAttribute("length", pContentLength + "");
            //System.out.println("We are currently reading item " + pItems);
            if (pContentLength == -1) {
              System.out.println("So far, " + pBytesRead + " bytes have been read.");

            } else {
              System.out.println("So far, " + pBytesRead + " of " + pContentLength
                      + " bytes have been read.");
            }
          }
        };
        upload.setProgressListener(progressListener);

        java.util.List<FileItem> items = upload.parseRequest(request);
        Node root = jcrSession.getRootNode();
        Node folder = null;


        org.apache.tika.mime.MimeTypes mt = new org.apache.tika.mime.MimeTypes();

        for (FileItem item : items) {

          String requestHost = request.getRemoteAddr();
          requestHost = requestHost.replaceAll("\\.", "-");
          requestHost = "localhost";
          Node node = NodeUtil.emailNode(requestHost, root);

          String id = item.getName().substring(0, item.getName().indexOf(".zip"));

          if (node.hasNode(id)) {
            node.getNode(id).remove();
          }

          Node folderNode = node.addNode(id, "nt:folder");

          //System.out.println(id + "????<br/>");
          ZipInputStream zis = new ZipInputStream(item.getInputStream());
          ZipEntry entry;
          ZipEntry metaEntry = null;
          ZipEntry messageBodyEntry = null;
          Properties meta = new Properties();
          java.io.ByteArrayInputStream messageBodyIS = null;
          while ((entry = zis.getNextEntry()) != null) {
            out.println(entry.getName() + "<br/>");
            System.out.println(entry.getName() + "<br/>");
            if (entry.isDirectory()) {
              continue;
            }
            if (entry.getName().equals("meta.txt")) {
              java.io.ByteArrayInputStream b = new ByteArrayInputStream(org.apache.commons.io.IOUtils.toByteArray(zis));
              metaEntry = entry;
              meta.load(b);

            } else if (entry.getName().startsWith("message.")) {

              messageBodyIS = new ByteArrayInputStream(org.apache.commons.io.IOUtils.toByteArray(zis));
              //Node newNode = contentNode.addNode(entry.getName(), "nt:file");
              messageBodyEntry = entry;

            } else {
              if (entry.getSize() < 1024 * 1024 * 10) {
                java.io.ByteArrayInputStream b = new ByteArrayInputStream(org.apache.commons.io.IOUtils.toByteArray(zis));
                Node newNode = folderNode.addNode(entry.getName(), "nt:file");
                Node thisCon = newNode.addNode("jcr:content", "nt:unstructured");
                thisCon.setProperty("jcr:mimeType", mt.getMimeType(entry.getName()).getName());
                thisCon.setProperty("jcr:data", b);
              } else {
                File t1 = File.createTempFile("temp", null);
                FileOutputStream fos = new FileOutputStream(t1);
                org.apache.commons.io.IOUtils.copy(zis, fos);
                fos.close();
                FileInputStream fis = new FileInputStream(t1);
                Node newNode = folderNode.addNode(entry.getName(), "nt:file");
                Node thisCon = newNode.addNode("jcr:content", "nt:unstructured");
                thisCon.setProperty("jcr:mimeType", mt.getMimeType(entry.getName()).getName());
                thisCon.setProperty("jcr:data", fis);
                // resource.setProperty("jcr:data", fis);
                t1.delete();
              }
            }
          }

          Node messageNode = folderNode.addNode(messageBodyEntry.getName(), "nt:file");
          Node contentNode = messageNode.addNode("jcr:content", "nt:unstructured");

          for (Object key : meta.keySet()) {
            contentNode.setProperty(key.toString(), meta.getProperty(key.toString()));
          }
          contentNode.setProperty("jcr:data", messageBodyIS);

          contentNode.setProperty("jcr:mimeType", mt.getMimeType(messageBodyEntry.getName()).getName());
          java.util.Calendar lastModified = java.util.Calendar.getInstance();
          lastModified.setTimeInMillis(messageBodyEntry.getTime());
          contentNode.setProperty("jcr:lastModified", lastModified);
        }
        jcrSession.save();
      } else {
        out.println("error");
      }
    } catch (Exception e) {
      e.printStackTrace();


    } finally {
      if (jcrSession != null) {
        jcrSession.logout();

      }
    }

%>


<%!
  public static Node fileNodeFromURL(String sUrl, Node root) throws Exception {
    // final URL currentURL = urls[i];
    // root.getNodes().hasNext() root.getNodes().nextR;

    String path = "";// urls[i].getPath();

    String host = "";
    if (!path.startsWith("http")) {
      path = sUrl;
    } else {
      URL url = new URL(sUrl);
      host = url.getHost();
    }
    List folderNames = new ArrayList();
    if (!host.isEmpty()) {
      folderNames.addAll(Arrays.asList(host.split("\\.")));
    }
    Collections.reverse(folderNames);
    if (!path.isEmpty()) {
      folderNames.addAll(Arrays.asList(path.split("/|\\\\")));
    }
    final String fileName = URLDecoder.decode((String) folderNames.remove(folderNames.size() - 1), "UTF-8").replaceAll(":", "_");
    System.out.println(folderNames);
    System.out.println(fileName);
    Node node = root;
    for (Iterator fn = folderNames.iterator(); fn.hasNext();) {
      String name = URLDecoder.decode((String) fn.next(), "UTF-8");
      name = name.replaceAll(":", "_");
      if (name.length() == 0) {
        continue;
      }
      if (!node.hasNode(name)) {
        node.addNode(name, "nt:folder");
        //System.out.println("added name=" + name);
      }
      node = node.getNode(name);
    }
    final Node file;
    if (!node.hasNode(fileName)) {
      file = node.addNode(fileName, "nt:file");
    } else {
      file = node.getNode(fileName);
    }
    return file;
  }
%>